package cn.itsource.hbc.user.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.hbc.user.contants.UserContants;
import cn.itsource.hbc.user.contants.WxInfoContants;
import cn.itsource.hbc.user.domain.LoginInfo;
import cn.itsource.hbc.user.domain.User;
import cn.itsource.hbc.user.domain.WxUser;
import cn.itsource.hbc.user.mapper.LoginInfoMapper;
import cn.itsource.hbc.user.mapper.UserMapper;
import cn.itsource.hbc.user.mapper.WxUserMapper;
import cn.itsource.hbc.user.service.IWxUserService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WxUserServiceImpl extends BaseServiceImpl<WxUser> implements IWxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    public AjaxResult login(Map<String, String> map) {

        // 从map对象中拿出前端传回的code验证码
        String code = map.get("code");
        // 替换
        String url= WxInfoContants.GET_ACK_URL.replace("APPID",WxInfoContants.APPID).replace("SECRET",WxInfoContants.SECRET).replace("CODE",code);

        // 获取传回参数url
        String wxRsult = HttpUtil.sendGet(url);
        // 获取json里面数据
        JSONObject jo = JSON.parseObject(wxRsult);
        // 获取openid
        String openid = jo.getString("openid");
        // 获取access_token
        String access_token = jo.getString("access_token");
        // 判断数据库中有没有openid，没有就是新用户，有就是老用户
        WxUser wxUser = wxUserMapper.loadByOpenId(openid);
        // 判断两张表的数据有没有t_wxuser、t_user
        // 说明有数据老用户
        if(wxUser!=null && wxUser.getUser()!=null) {
            // 拿到userid
            LoginInfo loginInfo = loginInfoMapper.loadByUid(wxUser.getUser().getId());
            return noPasswordlogin(loginInfo);
        }else {
            // 跳转到绑定用户页面
            return new AjaxResult("bindwechart.html?openid="+openid+"&access_token="+access_token);
        }

    }

    @Override
    @Transactional
    public AjaxResult bind(Map<String, String> map) {

        // 从map中获取传递数据
        String code = map.get("code");
        String openId = map.get("openId");
        String phone = map.get("phone");
        String access_token = map.get("access_token");

        // 对比验证码是否正确
        String codeAndeTimeInRedis = (String) redisTemplate.opsForValue().get(UserContants.BIND_CODE + ":" + phone);
        System.out.println("在redis中的验证码"+codeAndeTimeInRedis);

        // 把验证码截取出来
        String codeInRedis = codeAndeTimeInRedis.split(":")[0];
        System.out.println("截取出来的验证码"+codeInRedis);

        //和传回来的验证码进行比较,取反代表验证码不一致
        if(!codeInRedis.equals(code)){
            return new  AjaxResult("验证码有误请从新输入");
        }
        LoginInfo loginInfo =null;
        // 判断用户的手机号是否注册过
        User user = userMapper.loadByPhone(phone);
        // 用户手机号没注册过
        if (user==null){
            // 没注册过创建一个用户
            user = new User();
            user.setState(1);
            user.setUsername("p_"+phone);
            user.setPhone(phone);
            // 保存到数据库库
            userMapper.save(user);

             loginInfo = user2LoginInfo(user);
             // 保存到数据库
            loginInfoMapper.save(loginInfo);

        }
            // 获取用户登录信息保存在t_LoginInfo表中，关联
        String url = WxInfoContants.GET_USER_URL
                    .replace("OPENID",openId)
                    .replace("ACCESS_TOKEN",access_token);

        String wxInfoResult = HttpUtil.sendGet(url);

        System.out.println("wxInfoResult"+wxInfoResult);

        JSONObject jo = JSON.parseObject(wxInfoResult);
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(jo.getString("openid"));
        wxUser.setNickname(jo.getString("nickname"));
        wxUser.setSex(jo.getInteger("sex"));
        wxUser.setHeadimgurl(jo.getString("headimgurl"));
        wxUser.setUnionid(jo.getString("unionid"));
        wxUser.setAddress(jo.getString("country")+jo.getString("province")+jo.getString("city"));
        wxUser.setUser(user);

        // 操作数据库
        wxUserMapper.save(wxUser);
        if(loginInfo==null){
            loginInfo = loginInfoMapper.loadByUid(user.getId());
        }
        return noPasswordlogin(loginInfo);
    }

    private LoginInfo user2LoginInfo(User user) {
        LoginInfo info = new LoginInfo();
        BeanUtils.copyProperties(user,info);
        info.setDisable(1);
        info.setType(1);
        info.setUId(user.getId());
        return info;
    }


    public AjaxResult noPasswordlogin( LoginInfo loginInfo){

            // 获取token
            String token = UUID.randomUUID().toString();
            // 把登陆过得用户存入redis中
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);

    }
















}
